//
// Parse.cpp for parse in /home/druart_p/Work/math/201
// 
// Made by pierrick druart
// Login   <druart_p@epitech.net>
// 
// Started on  Mon Feb 13 10:55:53 2012 pierrick druart
// Last update Fri Feb 24 10:12:03 2012 pierrick druart
//

#include "Parse.hh"
#include "Prob.hh"

#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>

  //##############################//
 //   Constructor & Destructor   // 
//##############################//
Parser::Parser()
{
  Prob calc;
  std::string	flux;

  getline(std::cin, flux);
  this->parseFlux(flux);
  calc.setList(this->list);
  calc.probAll();
  calc.probEt();
  calc.probOr();
  std::cout << flux << " = " << std::setprecision(3) << calc.getResult() << std::endl;
}

Parser::Parser(const std::string& file)
{
  Prob calc;
  std::list<std::string>::iterator it;
  std::list<std::string>::iterator it2;

  this->getFluxFromFile(file);
  for (it = this->_fluxlist.begin(); it != this->_fluxlist.end(); it++)
    {
      this->parseFlux(*it);
      calc.setList(this->list);
      calc.probAll();
      calc.probEt();
      calc.probOr();
      std::cout << *it << " = " << std::setprecision(3) << calc.getResult() << std::endl;
      this->list.clear();
    }
}

Parser::~Parser() {}

  //##############################//
 //       Getter & Setter        // 
//##############################//

const std::list<std::string>&	Parser::getFluxList() const
{
  return this->_fluxlist;
}

const std::list<std::string>&		Parser::getList() const
{
  return this->list;
}
  //##############################//
 //            Function          // 
//##############################//

void	Parser::getFluxFromFile(const std::string & file)
{
  std::string line;
  const char *test = file.c_str();
  std::ifstream myfile(test);

  if (myfile.is_open())
    {
      while (myfile.good())
	{
	  getline(myfile,line);
	  this->_fluxlist.push_back(line);
	}
      myfile.close();
    }
}

void	Parser::parseFlux(const std::string & flux)
{
  std::string	tmp;
  unsigned int	i;
  unsigned int	j = 0;

  for (i = 0; i < flux.length(); i++)
    {
      if (flux.at(i) == '+')
	{
	  tmp = flux.substr(j, i - j);
	  j = i+1;
	  this->list.push_back(tmp);
	  this->list.push_back("+");
	}
      if (flux.at(i) == 'x')
	{
	  tmp = flux.substr(j, i - j);
	  j = i+1;
	  this->list.push_back(tmp);
	  this->list.push_back("x");
	}
    }
  tmp = flux.substr(j, i - j);
  this->list.push_back(tmp);
}


